<?php
namespace Database;

class Resource extends Base
{

    public function __construct()
    {
        $this->setModel(MODEL_RESOURCE);
    }

    public function getGrade1List($categoryId = 0, $page = 1, $pageSize = 10, $userId = 0)
    {
        $now = getDateTime();
        $sql = $this->getSql();
        $sql->field('*');
        $sql->table($this->getTable());
        $sql->where('dry_category', '=', $categoryId);
        $sql->andWhere('dry_status', '=', 1);
        $sql->andWhere('dry_grade', '=', 1);
        $sql->andWhere('dry_start_time', '<', $now['date_time']);
        $sql->andWhere('dry_end_time', '>', $now['date_time']);
        if(!in_array($userId, [8, 9, 10, 11])){
            $sql->andWhere('dry_test', '=', 0);
        }
        $sql->setOrder('dry_data_sort', 'asc');
        $sql->setPage($page);
        $sql->setPageSize($pageSize);
        $sql->setLimit();
        $list = $this->fetchAll($sql->get());
        $count = $this->fetchColumn($sql->getTotalSql());
        return [
            'list' => $list,
            'count' => $count
        ];
    }

    public function getGrade123List($parentId = 0)
    {
        $now = getDateTime()['date_time'];
        $table = $this->getTable();
        $sql = "
        (
            select * from {$table} where id={$parentId}
        )
        union
        (
            select
            *
            from {$table}
            where dry_parent={$parentId} and dry_status=1 and dry_grade=2 and '{$now}'>dry_start_time and '{$now}'<dry_end_time
            order by dry_data_sort asc
        )
        union
        (
            select
            c.*
            from {$table} r
            left join {$table} c on c.dry_parent=r.id
            where r.dry_parent={$parentId} and c.dry_status=1 and c.dry_grade=3 and '{$now}'>c.dry_start_time and '{$now}'<c.dry_end_time
            order by c.dry_data_sort asc
        )
        ";
        return $this->fetchAll($sql);
    }

}